package net.gdface.jmx;

import javax.management.DynamicMBean;
import javax.management.MBeanInfo;

import static net.gdface.utils.ConditionChecks.checkNotNull;

/**
 * 基于{@link DynamicMBeanDecorator},实现{@link DynamicMBean}接口封装<br>
 * 
 * @author guyadong
 *
 * @param <I> 接口类型
 */
public class DynamicMBeanDelegate<I> extends BaseMBeanDelegate<I>{
	private final DynamicMBeanDecorator dynamicMBeanDecorator;

	@SuppressWarnings("unchecked")
	public DynamicMBeanDelegate(MBeanInfo mbeanInfo,Object delegate) {
		super((Class<I>)JMXSupport.getMBeanClass(checkNotNull(mbeanInfo,"mbeanInfo is null")));
		this.dynamicMBeanDecorator = new DynamicMBeanDecorator(
				mbeanInfo, delegate);
	}
	public DynamicMBeanDelegate(MBeanInfo mbeanInfo) {
		this(mbeanInfo,null);
	}
	
	public DynamicMBeanDelegate<I> withPort(int port){
		setPort(port);
		return this;
	}
	@Override
	protected Object getMBean(){
		return dynamicMBeanDecorator;
	}
	/**
	 * 返回当前代理接口实例
	 * @return context 接口实例
	 */
	public I delegate() {
		return mbeanClass.cast(dynamicMBeanDecorator.delegate());
	}
	public Object delegateObject() {
		return dynamicMBeanDecorator.delegate();
	}
	/**
	 * 指定代理的应用上下文实例
	 * @param delegate 代理实例,为{@code null}忽略
	 * @return 当前对象
	 */
	public DynamicMBeanDelegate<I> delegate(Object delegate) {
		if(dynamicMBeanDecorator != null){
			dynamicMBeanDecorator.delegate(delegate);
		}
		return this;
	}
	/**
	 * 设置日志参数
	 * @param logError 是否输出方法调用异常信息
	 * @param trace 是否输出方法调用异常堆栈,logError为{@code true}时有效
	 * @return 当前对象
	 */
	public DynamicMBeanDelegate<I> setLogConfig(boolean logError,boolean trace) {
		if(null != dynamicMBeanDecorator){
			dynamicMBeanDecorator.setLogConfig(logError, trace);
		}
		return this;
	}
}


